package me.eleme.anubis.openapi.utils;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


/**
 * @author liuzhiyong
 */
@Slf4j
public class Base64Util {

    public static String encode(byte[] binaryData) {
        Base64.Encoder encoder = Base64.getEncoder();
        return new String(encoder.encode(binaryData), StandardCharsets.UTF_8);
    }

    /**
     * 本地文件（图片、excel等）转换成Base64字符串
     * @param imgPath
     */
    public static String convertFileToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组进行Base64编码，得到Base64编码的字符串
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);
        return base64Str;
    }
}
